package wang.conge.javasedemo.core.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionTest {

	public static void main(String[] args) {
		Lock lock = new ReentrantLock();
		Condition condition = lock.newCondition();
		
		lock.lock();//1.主线程获取锁
		
		System.out.println("main thread lock and run");//2.主线程业务执行
		
		new Thread (()->{
			lock.lock();//6.主线程阻塞让出lock锁，子线程获取锁
			
			System.out.println("child thread lock and run");//7.子线程业务执行
			
			condition.signalAll();//唤醒等待此condition下面的所有线程//8.子线程唤醒等待在condition下面的线程
			
			System.out.println("child thread unlock");
			lock.unlock();//9.子线程unlock,让出锁
		}).start();//4.子线程start
		
		try {
			condition.await();//5.主线程执行condition.await()，让出condition对应的lock锁， 主线程进入阻塞状态
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		System.out.println("main thread continue run");//10.因为被子线程唤醒，而且子线程让出锁，主线程重新获取锁，继续运行
		
		System.out.println("main thread unlock");
		lock.unlock();//11.主线程unlock,让出锁，结束整个流程
	}

}
